﻿using AutoMapper;
using MediatR;
using System.Security;
using Traceability.Commont.DBContexts;
using Traceability.Commont.Domains;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.UsersFile;
using Traceability.Commont.Infrastructures.Interfaces;

namespace Traceability.Api.Applications.Roless
{
    public class RolesCreateHander : IRequestHandler<RolesCreateCommand, Resqults>
    {
        private readonly IBateRepository<Roles> roles;
        private readonly IBateRepository<RolesPermissiont> rolesPermission;
        private readonly IMapper mapper;
        private readonly EFDBContext db;

        public RolesCreateHander(IBateRepository<Roles> roles,
                                 IBateRepository<RolesPermissiont> rolesPermission,
                                 IMapper mapper,
                                 EFDBContext db)
        {
            this.roles = roles;
            this.rolesPermission = rolesPermission;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<Resqults> Handle(RolesCreateCommand request, CancellationToken cancellationToken)
        {
            var cou = 0;
            try
            {
                RolesCreateDTO role = mapper.Map<RolesCreateDTO>(request);
                Roles roless = new Roles();
                roless.RolesName = role.RolesName;
                cou +=await roles.Add(roless);
                foreach (var item in role.Ids)
                {
                    var rolesPer = new RolesPermissiont()
                    {
                        RolesId = roless.RolesId,
                        PermissionsId = item
                    };
                   cou+=await rolesPermission.Add(rolesPer);
                }

                Resqults res = new Resqults();
                res.Code = cou;
                return res;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
